package linker;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;

import data.Statement;

public class SourceSampling {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if (args.length < 1) {
			System.out
					.println("please specify the path for config file as parameter");
			return;

		}
		String config = args[0];
		Properties pre = new Properties();
		try {
			pre.load(new FileInputStream(config));
		} catch (FileNotFoundException e) {
			System.out.println("cannot find config file");
			return;
		} catch (IOException e) {
			System.out.println("cannot open config file");
			return;
		}

		int size = 100;
		if (pre.containsKey("size"))
			size = Integer.valueOf(pre.getProperty("size"));
		String output = pre.getProperty("output");
		String input = pre.getProperty("input");
		URL url;

		Parser par = new Parser(null);
		try {
			par.open(input);
		} catch (FileNotFoundException e) {
			System.out.println("cannot find input file");
			return;
		} catch (IOException e) {
			System.out.println("cannot open input file");
			return;
		}
		File outDir = new File(output);
		if (!outDir.exists())
			outDir.mkdir();
		else if (!outDir.isDirectory()) {
			System.out.println("output is not a directory");
			return;
		}
		File outFile;
		FileOutputStream out;
		int fileCounter = 0;
		int sizeCounter = 1;
		outFile = new File(outDir, "sampling" + fileCounter + ".nt");
		try {
			outFile.createNewFile();
			out = new FileOutputStream(outFile);
			System.out.println("processing...");
			while (par.hasNext()) {
				Statement st = par.nextStatement();
				if (sizeCounter >= size) {
					sizeCounter = 1;
					fileCounter++;
					outFile = new File(outDir, "sampling" + fileCounter + ".nt");
					outFile.createNewFile();
					out = new FileOutputStream(outFile);
				}
				out.write(st.toString().getBytes());
		
			}
		} catch (IOException e) {
			System.out.println("cannot write new output file");
		}

		System.out.println("sampling complete");

	}

}
